<template>
	<div class="adminMain" v-loading="load.load">
		<el-row class="tableBtnTop">
			<el-date-picker type="daterange" v-model="time" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width:400px;margin-right:15px;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" popper-class="index_promotionData_daterange_popper_class"></el-date-picker>
			<el-button class="f1" @click="getList">立即搜索</el-button>
			<el-button class="f1" style="margin-left:15px;" @click="findRecovery" v-if="tab.list">查询回本情况</el-button>
			<span class="tableBtnSpan">数据将会每隔15分钟更新一次</span>
		</el-row>
		<el-tabs type="card" v-model="tab.value" v-if="tab.list" @tab-click="tabChange">
			<el-tab-pane :label="item.label" :name="item.key" lazy v-for="(item, index) in tab.list">
				<el-table :data="tableData" border>
					<el-table-column prop="time" label="时间" :show-overflow-tooltip="true" fixed width="150">
						<template slot-scope="scope">{{ scope.row.total_date }}</template>
					</el-table-column>
					<el-table-column prop="" label="新复金额" :show-overflow-tooltip="true">
						<template slot-scope="scope">
							<div style="font-size:12px;">今日新购：{{ scope.row.today_purchase }}</div>
							<div style="font-size:12px;">非今日新购：{{ scope.row.non_today_purchase }}</div>
							<div style="font-size:12px;">复购：{{ scope.row.repurchase_purchase }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="" label="今日新购Roi" :show-overflow-tooltip="true">
						<template slot-scope="scope">
							{{ (scope.row.today_purchase_roi * 100).toFixed(2) }}%
						</template>
					</el-table-column>
					<el-table-column prop="totalWaterFlow" label="总流水" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.total_revenue }}</template>
					</el-table-column>
					<el-table-column prop="investmentExpenditure" label="投放支出" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.advertising_expenditure }}</template>
					</el-table-column>
					<el-table-column prop="regNum" label="注册人数" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.registered_users }}</template>
					</el-table-column>
					<el-table-column prop="numberNewBuyers" label="新购人数" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.new_purchase_users }}</template>
					</el-table-column>
					<el-table-column prop="numberRepeatNuyers" label="复购人数" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.repurchase_users }}</template>
					</el-table-column>
					<el-table-column prop="activationPurchaseRate" label="注册购买率" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ (scope.row.registration_purchase_rate * 100).toFixed(2) }}%</template>
					</el-table-column>
					<el-table-column prop="singlePaidCost" label="新购用户付费成本" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.new_purchase_user_cost }}</template>
					</el-table-column>
					<el-table-column prop="defeatVictory" label="税后亏盈" :show-overflow-tooltip="true">
						<template slot-scope="scope">
							<span style="font-weight: bold;" :style="{ color: scope.row.subsequent_profit_loss >= 0 ? '#F30' : '#63bd42' }">{{ scope.row.subsequent_profit_loss }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="singlePaidCost" label="最后更新时间" :show-overflow-tooltip="true">
						<template slot-scope="scope">{{ scope.row.updated_at || "-" }}</template>
					</el-table-column>
					<el-table-column prop="user" label="操作" :show-overflow-tooltip="true" v-if="tab.value !== '0'">
						<template slot-scope="scope">
							<div class="tableBtn">
								<a class="color" @click="reFind(scope.row)">重新查询</a>
							</div>
						</template>
					</el-table-column>
				</el-table>
				<div class="paginationBlock">
					<el-pagination layout="prev, pager, next, sizes, total" @size-change="getList" @current-change="getList" :total="total" :current-page.sync="page" :page-size.sync="limit" ></el-pagination>
				</div>
			</el-tab-pane>
		</el-tabs>
		<el-dialog :visible.sync="recovery.show" title="查询回本情况" width="1000px" :close-on-click-modal="false">
			<div class="AddOrderFormDialog-root" v-if="recovery.tab">
				<el-form label-position="top">
					<el-form-item label="推广渠道" required>
						<el-row>
							<el-radio-group v-model="recovery.tab.value" size="mini">
								<el-radio-button v-for="(item, index) in recovery.tab.list" :label="item.key">
									{{ item.label }}
								</el-radio-button>
							</el-radio-group>
						</el-row>
					</el-form-item>
				</el-form>
				<el-form label-position="top">
					<el-form-item label="用户注册时间范围" required>
						<el-date-picker v-model="recovery.time" type="daterange" range-separator="至" start-placeholder="开始注册日期" end-placeholder="结束注册日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width:100%;"></el-date-picker>
						<div style="margin-top:10px;" v-if="monthArray.length > 0">
							<el-button size="mini" round @click="recovery.time = item.time" v-for="(item, index) in monthArray">{{ item.name }}</el-button>
						</div>
					</el-form-item>
				</el-form>
				<div v-if="recovery.data">
					<el-form label-position="top">
						<el-form-item label="">
							<div>回本情况：</div>
							<div style="line-height:30px;">
								-> 推广渠道为 “{{ recovery.data.channel }}” 的该批次用户推广支出为{{ recovery.data.advertising_expenditure }}元<br />
								-> 当日消费了{{ recovery.data.total_time.pre_tax }}元（税后{{ recovery.data.total_time.after_tax }}元）<br/>
								-> 累计消费了{{ recovery.data.total_all.pre_tax }}元（税后{{ recovery.data.total_all.after_tax }}元）<br/>
								-> 综合税后回本率<font :color="recovery.data.after_tax_rate >= 0 ? '#F30' : '#63bd42'">{{ recovery.data.after_tax_rate }}%</font> <br/>
								-> 综合税后<font style="font-weight:bold;" :style="{ color: recovery.data.after_tax_profit >= 0 ? '#F30' : '#63bd42' }">{{ recovery.data.after_tax_profit >= 0 ? '盈利' : '亏损' }}{{ recovery.data.after_tax_profit }}元</font> 
							</div>
						</el-form-item>
					</el-form>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="recovery.show = false">取消</el-button>
				<el-button type="primary" @click="findRecoveryPost" :loading="recovery.load.load">查询</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		computed: {
			
			// 获取到现在有多少个月
			monthArray(){
				let _this = this;
				const startDate = new Date('2024-01-01');  
				const endDate = new Date(this.app.toTime("", "YYYY-MM-DD"));  
				let months = [];  
				let currentDate = new Date(startDate);  
				while (currentDate <= endDate) {  
					const month = currentDate.getMonth() + 1; // getMonth() 是从0开始的，所以我们需要加1  
					const year = currentDate.getFullYear();  
					
					// 创建开始日期的Date对象，设置为当月的第一天  
					const startOfMonth = new Date(year, month - 1, 1 + 1).toISOString().slice(0, 10);  
					  
					// 创建结束日期的Date对象，设置为下个月的第一天（当前月的最后一天）  
					const endOfMonth = new Date(year, month, 1).toISOString().slice(0, 10);  
					
					months.push({  // 确保月份是两位数  
						name: `${year}年${month < 10 ? '0' + month : month}月`,
						time: [startOfMonth, endOfMonth]
					}); 
					currentDate.setMonth(currentDate.getMonth() + 1); // 将日期移动到下一个月  
				}  
				return months; 
			},
			
		},
		data() {
			return {
				
				// 是否处于加载中
				load: { load: false },
				
				// 表格数据
				tableData: [],
				
				// 当前页数
				page: this.$route.query.page ? parseInt(this.$route.query.page) : 1,
				
				// 每页条数
				limit: this.$route.query.limit ? parseInt(this.$route.query.limit) : this.app.limit,
				
				// 总数
				total: this.$route.query.total ? parseInt(this.$route.query.total) : 0,
				
				// 时间
				time: this.$route.query.time ? this.$route.query.time.split(",") : [],
				
				// tab选项卡
				tab: {
					value: this.$route.query.channel || "0",
					list: null
				},
				
				// 回本状态的显示隐藏
				recovery: {
					load: { load: false },
					show: false,
					tab: null,
					time: [],
					data: null,
				},
				
			};
		},
		methods: {
			
			// 重新查询
			reFind(row){
				let _this = this;
				console.log()
				_this.app.ajax({
					url: "/admin/channelDeficit/refresh",
					method: "POST",
					data: {
						channel_id: row.channel_id,
						total_date: row.total_date,
					},
					load: _this.load,
					success(res){
						_this.$notify({title: '提示',message: res.msg, type: 'success'});
					}
				});
			},
			
			// tab切换
			tabChange(e){
				this.tab.value = e.name;
				this.tableData = [];
				this.total = 0;
				this.page = 1;
				this.getList();
			},
			
			// 加载列表
			getList(){
				let _this = this;
				_this.app.ajax({
					url: "/admin/channelDeficit/index",
					method: "POST",
					data: {
						limit: _this.limit,
						page: _this.page,
						time: _this.time ? _this.time.join(",") : "",
						channel: _this.tab.value
					},
					load: _this.load,
					changeUrl: true,
					success(res){
						_this.total = res.data.total;
						_this.tableData = res.data.list;
						
						let tabList = [];
						res.data.filter.map((item) => {
							if(item.field === "channel"){
								item.select.map((prop) => {
									tabList.push({ label: prop.label, key: prop.value + "" });
								});
							}
						});
						_this.tab.list = tabList;
					}
				})
			},
			
			// 查询回本弹窗打开
			findRecovery(){
				let _this = this;
				_this.recovery.tab = JSON.parse(JSON.stringify(_this.tab));
				_this.recovery.time = [];
				_this.recovery.data = null;
				_this.recovery.show = true;
			},
			
			// 查询回本情况请求
			findRecoveryPost(){
				let _this = this;
				_this.app.ajax({
					url: "/admin/channelDeficit/total",
					method: "POST",
					data: {
						time: _this.recovery.time ? _this.recovery.time.join(",") : "",
						channel: _this.recovery.tab.value
					},
					load: _this.recovery.load,
					success(res){
						_this.recovery.data = res.data;
					}
				});
			},
			
		},
		mounted(){
			this.getList();
		}
	};
</script>

<style lang="scss" scoped>
	.adminMain{
		min-height: 500px;
	}
	.tableBtnSpan{
		flex: 1;
		text-align: right;
		font-size: 12px;
		color: #999;
	}
</style>